/* 
	1. 抓取 视觉中国首页图片
	2. 分析网站内容 cheerio
	3. 将抓取的图片保存到本地
*/
const http = require("https");
const fs = require("fs");
const cheerio = require("cheerio")


http.get("https://www.vcg.com/", (res) => {

	const { statusCode } = res;
	const contentType = res.headers["content-type"];

	let error
	if(statusCode !== 200){
		error = new Error("请求失败\n"+`状态吗：${statusCode}`);
	}else if(!/^application\/json/.test(contentType)){
		error = new Error('无效的 content-type.\n' + `期望的是 application/json 但接收到的是 ${contentType}`);
	}

	res.setEncoding("utf-8")
	let rawData = "";
	let $;
	res.on('data',(chunk)=>{
		rawData += chunk;
	})
	res.on("end",()=>{
		// console.log(rawData)
		$ = cheerio.load(rawData);
		let $img = $("img");
		let imgTxt = "";
		$img.each((index,item)=>{
			console.log(item.attr("img"));
			imgTxt += $(item).attr("img")+"\n";
		})
		
		fs.writeFileSync("./shijue.txt",imgTxt);
	})
	res.on("error",(e)=>{

	})

})

